package com.tomehay.termprojectmanage_server.service.impl;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tomehay.termprojectmanage_server.enums.ResponseCode;
import com.tomehay.termprojectmanage_server.mapper.*;
import com.tomehay.termprojectmanage_server.pojo.Model.*;
import com.tomehay.termprojectmanage_server.pojo.Model.PersonalTask;
import com.tomehay.termprojectmanage_server.pojo.VO.PersonalTaskVO;
import com.tomehay.termprojectmanage_server.pojo.VO.ResultVO;
import com.tomehay.termprojectmanage_server.service.PersonalTaskService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * (PersonalTask表)服务实现类
 *
 * @author makejava
 * @since 2023-06-24 13:40:22
 */
@Service("personalTaskService")
public class PersonalTaskServiceImpl extends ServiceImpl<PersonalTaskMapper, PersonalTask> implements PersonalTaskService {
    @Resource
    private PersonalTaskMapper personalTaskMapper;
    @Resource
    private GroupTaskMapper groupTaskMapper;
    @Resource
    private AllocationMapper allocationMapper;
    @Resource
    private TermprojectMapper termprojectMapper;
    @Resource
    private CourseMapper courseMapper;
    @Resource
    private TermMapper termMapper;
    @Value("${filePath}")
    private String filePath;
    @Resource
    private GroupMemberMapper groupMemberMapper;
    @Resource
    private StudentMapper studentMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public PersonalTask selectById(Integer id) {
        return this.personalTaskMapper.selectById(id);
    }

    /**
     * 分页查询
     *
     * @param start 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<PersonalTask> selectPage(int start, int limit) {
//        return this.personalTaskMapper.selectPage(start, limit);
        return null;
    }

    /**
     * 查询所有
     *
     * @return 实例对象的集合
     */
     @Override
     public List<PersonalTask> selectAll() {
        return this.personalTaskMapper.selectAll();
     }

    /**
     * 根据条件查询
     *
     * @return 实例对象的集合
     */
    @Override
    public List<PersonalTask> selectList(PersonalTask personalTask) {
//        return this.personalTaskMapper.selectList(personalTask);
        return null;
    }

    /**
     * 新增数据
     *
     * @param personalTask 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(PersonalTask personalTask) {
        return this.personalTaskMapper.insert(personalTask);
    }

    /**
     * 批量新增
     *
     * @param personalTasks 实例对象的集合
     * @return 生效的条数
     */
    @Override
    public int batchInsert(List<PersonalTask> personalTasks) {
        return this.personalTaskMapper.insertBatch(personalTasks);
    }

    /**
     * 修改数据
     *
     * @param personalTask 实例对象
     * @return 实例对象
     */
    @Override
    public PersonalTask update(PersonalTask personalTask) {
        this.personalTaskMapper.updateSelective(personalTask);
        return this.selectById(personalTask.getId());
    }

    @Override
    public List<PersonalTask> list(Integer id) {
        return null;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public int deleteById(Integer id) {
        return this.personalTaskMapper.deleteById(id);
    }

    @Override
    public int count() {
        return 0;
    }

    @Override
    public PersonalTask getDetailById(Integer id) {
        return personalTaskMapper.getById(id);
    }

    @Override
    public int savepersonalTask(PersonalTask personalTask) {
//        return baseMapper.savePersonalTask(personalTask);
        personalTask.setCreateTime(LocalDateTime.now());
        personalTask.setStatus(0);
        personalTask.setPersonalTaskNo("325"+System.currentTimeMillis());
        return baseMapper.insert(personalTask);
    }

    @Override
    public List<PersonalTask> selectAllPersonalTask(Integer pid, Integer gid, Integer gmId) {
        System.out.println(gid + " " + gmId);
        List<Allocation> allocations = allocationMapper.selectAllByGroupIdAndTermProjectId(gid, pid);
        List<GroupTask> groupTasks = new ArrayList<>();
        for (Allocation allocation : allocations) {
            List<GroupTask> groupTasks1 = groupTaskMapper.selectAllByAllocationId(allocation.getId());
            groupTasks.addAll(groupTasks1);
        }
        List<PersonalTask> allGroupTask = new ArrayList<>();
        for (GroupTask task: groupTasks) {
            List<PersonalTask> allByGroupTaskId = personalTaskMapper.getAllByGroupTaskIdAndDirector(task.getId(), gmId);
            allGroupTask.addAll(allByGroupTaskId);
        }
        return allGroupTask;
    }

    @Override
    public ResultVO<Void> UpLoadCode(MultipartFile multipartFile, int id) throws IOException {
        PersonalTask personalTask = personalTaskMapper.selectById(id);
        GroupTask groupTask = groupTaskMapper.selectById(personalTask.getGroupTaskId());
//        groupTask.setStatus(1);

        Termproject termproject = termprojectMapper.getTermProjectByAllocation(groupTask.getAllocationId());
        Course course = courseMapper.selectById(termproject.getCourseId());
        String TermName = termMapper.getTermName(course.getTermId());

        String path = filePath+"\\"+TermName+"\\"+course.getCourseName()+"\\"+termproject.getTitle()+"\\代码\\"+ personalTask.getDirector() + "\\" +multipartFile.getOriginalFilename();
        System.out.println(path);

        File file = new File(path);
        createFile(file);
        multipartFile.transferTo(file);

        personalTask.setCode(path);
        personalTaskMapper.updateById(personalTask);

        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<Void> UpLoadDoc(MultipartFile multipartFile, int id) throws IOException {
        PersonalTask personalTask = personalTaskMapper.selectById(id);
        GroupTask groupTask = groupTaskMapper.selectById(personalTask.getGroupTaskId());
//        groupTask.setStatus(1);

        Termproject termproject = termprojectMapper.getTermProjectByAllocation(groupTask.getAllocationId());
        Course course = courseMapper.selectById(termproject.getCourseId());
        String TermName = termMapper.getTermName(course.getTermId());

        String path = filePath+"\\"+TermName+"\\"+course.getCourseName()+"\\"+termproject.getTitle()+"\\代码\\"+ personalTask.getDirector() + "\\" +multipartFile.getOriginalFilename();
        System.out.println(path);

        File file = new File(path);
        createFile(file);
        multipartFile.transferTo(file);

        personalTask.setDocument(path);
        personalTaskMapper.updateById(personalTask);

        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<Void> FinishGroupTask(int id) {
//        UpdateWrapper updateWrapper = new UpdateWrapper<>();
//        updateWrapper.set("status",2);
//        updateWrapper.eq("id",id);
        PersonalTask task = personalTaskMapper.getById(id);
        task.setStatus(2);
        personalTaskMapper.updateSelective(task);
//        personalTaskMapper.update(null,updateWrapper);
        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<Void> DeleteCode(int id, String path) {
        PersonalTask personalTask = personalTaskMapper.selectById(id);
        GroupTask groupTask = groupTaskMapper.selectById(personalTask.getGroupTaskId());
        personalTask.setCode(null);

        LambdaUpdateWrapper<PersonalTask> lambdaUpdate = Wrappers.lambdaUpdate();
        //构建where条件根据id修改
        lambdaUpdate.eq(PersonalTask::getId, personalTask.getId());
        //name属性为空时可以修改字段为NULL
        if (StringUtils.isEmpty(personalTask.getCode())) lambdaUpdate.set(PersonalTask::getCode, null);
        //此时生成的SQL语句为update order set price = 3.8, name = null where id = 1
        super.update(personalTask, lambdaUpdate);


        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }

        return new ResultVO<>(ResponseCode.OK);
    }

    @Override
    public ResultVO<Void> DeleteDoc(int id, String path) {
        PersonalTask personalTask = personalTaskMapper.selectById(id);
        GroupTask groupTask = groupTaskMapper.selectById(personalTask.getGroupTaskId());
        personalTask.setDocument(null);

        LambdaUpdateWrapper<PersonalTask> lambdaUpdate = Wrappers.lambdaUpdate();
        //构建where条件根据id修改
        lambdaUpdate.eq(PersonalTask::getId, personalTask.getId());
        //name属性为空时可以修改字段为NULL
        if (StringUtils.isEmpty(personalTask.getDocument())) lambdaUpdate.set(PersonalTask::getDocument, null);
        //此时生成的SQL语句为update order set price = 3.8, name = null where id = 1
        super.update(personalTask, lambdaUpdate);

        File file = new File(path);
        if (file.exists()){
            file.delete();
        }
        personalTaskMapper.updateById(personalTask);
        return new ResultVO<>(ResponseCode.OK);
    }

    public static void createFile(File file) {
        if (file.exists()) {
            System.out.println("File exists");
        } else {
//            System.out.println("File not exists, create it ...");
            //getParentFile() 获取上级目录(包含文件名时无法直接创建目录的)
            if (!file.getParentFile().exists()) {
//                System.out.println("not exists");
                //创建上级目录
                file.getParentFile().mkdirs();
            }
            try {
                //在上级目录里创建文件
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public ResultVO<List<PersonalTaskVO>> GetByGroupTaskID(int id) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_task_id",id);
        List<PersonalTask> personalTasks = personalTaskMapper.selectList(queryWrapper);

        List<PersonalTaskVO> personalTaskVOS = new ArrayList<>();

        for (PersonalTask personalTask: personalTasks) {
            PersonalTaskVO personalTaskVO = new PersonalTaskVO();
            BeanUtil.copyProperties(personalTask,personalTaskVO);

            personalTaskVO.setTaskStatus(PersonalTask.mMap.get(personalTask.getStatus()));
            personalTaskVO.setDirectorName(GroupMember.GetMemberName(
                    groupMemberMapper,
                    personalTaskVO.getDirector(),
                    studentMapper));

            personalTaskVOS.add(personalTaskVO);
        }

        return new ResultVO<>(ResponseCode.auto(personalTaskVOS),personalTaskVOS);
    }



}

